# -*- coding: utf-8 -*-
import base64
import hashlib
import json
import random
import string
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '300021': {  # 新稻米支付 支付宝H5 3.5% 10-5000 dwc
        'API_KEY': '54b7a1f2ed6d3c5509b467e86294a6c6',
        'gateway': 'http://api.sxpay888.com/v1/com/quartet/api/order/uniteCreate',
        'query_gateway': 'http://api.sxpay888.com/v1/com/quartet/api/order/query',
    },
    '300020': {  # 新稻米支付 支付宝H5 3.5% 10-5000 witch
        'API_KEY': 'e84f1aa1424c82828b350f3b28ff9434',
        'gateway': 'http://api.sxpay888.com/v1/com/quartet/api/order/uniteCreate',
        'query_gateway': 'http://api.sxpay888.com/v1/com/quartet/api/order/query',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        _LOGGER.info("newdaomipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '100001'
    return '100001'


def _get_random_string():
    return ''.join(random.sample(string.ascii_letters + string.digits, 11))


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def base64ToString(b):
    return base64.b64decode(b).decode('utf-8')


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merch_id', app_id),
        ('version', '10'),
        ('signtype', '0'),
        ('timestamp', int(round(time.time() * 1000))),
        ('norce_str', _get_random_string()),
        ('detail', 'NewDaoMiPay'),
        ('out_trade_no', pay.id),
        ('money', int(pay_amount * 100)),
        ('channel', _get_pay_type(service)),
        ('callback_url', '{}/pay/api/{}/newdaomipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('ip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("newdaomipay create: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['out_trade_no'])
    response = requests.post(_get_gateway(app_id), data=parameter_dict, timeout=5)
    body = base64ToString(json.loads(response.text)['body'])
    _LOGGER.info("newdaomipay response status is: %s,data is: %s,body is: %s", response.status_code, response.text,
                 body)
    return {'charge_info': json.loads(body)['payurl']}


# OK
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    _LOGGER.info("newdaomipay request body is: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("newdaomipay notify data: %s, order_id is: %s", data, data['out_trade_no'])
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('newdaomipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = int(data['status'])
    trade_no = data['orderid']
    total_fee = float(data['paymoney']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }

    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 1:
        _LOGGER.info('newdaomipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    dct = OrderedDict((
        ('merch_id', int(app_id)),
        ('version', '10'),
        ('signtype', '0'),
        ('timestamp', int(round(time.time() * 1000))),
        ('norce_str', _get_random_string()),
        ('out_trade_no', str(pay_id)),
    ))
    dct['sign'] = generate_sign(dct, api_key)
    _LOGGER.info('newdaomipay query data: %s, order_id is: %s', json.dumps(dct), dct['out_trade_no'])
    response = requests.post(_get_query_gateway(app_id), data=dct, timeout=3)
    _LOGGER.info('newdaomipay query rsp: %s', response.text)
    data = json.loads(base64ToString(json.loads(response.text)['body']))
    if response.status_code == 200:
        trade_status = int(data['status'])
        total_fee = float(data['money']) / 100.0
        trade_no = int(data['orderid'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }
        if trade_status == 1:
            _LOGGER.info('newdaomipay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id, total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('newdaomipay data error, status_code: %s', response.status_code)
